﻿using CPPEI.Coolzon.Common;
using CPPEI.Coolzon.ServiceProxy.DataServiceRef;
using CPPEI.Coolzon.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CPPEI.Coolzon.UI.DataPartLib
{
    /// <summary>
    /// DataPartGrid.xaml 的交互逻辑
    /// </summary>
    [XPartIcon("pack://application:,,,/CPPEI.Coolzon.UI.DataPartLib;component/Images/PartIcons/表格.png")]
    [System.ComponentModel.DisplayName("表格")]
    public partial class DataPartGrid : DataPart
    {
        #region fields
        private List<GridColumn> _leafColumns;
        private int _PageCount;
        private int _HeaderCount;
        private DataResult _dataResult;
        private Dictionary<int, List<DataSeries>> _dataPage = new Dictionary<int, List<DataSeries>>();
        private string[] _asNullValueSegments = null;

        // 表头占据多少行
        private int _headerGridRowCount;

        /// <summary>
        /// 行索引
        /// </summary>
        private int _pageIndex;
        /// <summary>
        /// 需要显示的行数，如果有配置按配置来，否则按数据的实际行数来决定
        /// </summary>
        private int _displayRowCount;


        /// <summary>
        /// 表格的行
        /// </summary>
        private List<DataGridRow> Rows { get; set; }

        /// <summary>
        /// 滚动动画
        /// </summary>
        private System.Windows.Threading.DispatcherTimer _loopTimer;

        IDataResultSpliter _dataSpliter;
        #endregion

        public DataPartGrid()
        {
            XRowFont = new FontFamily("微软雅黑");
            XOddRowFont = XRowFont;
            XHeaderFont = XRowFont;
            XAsNullValues = "0,0%,0.0,0.00,0.00%,0.0%";
            XNullValueText = "—";
            XHeaderHeight = 30;

            Rows = new List<DataGridRow>();
            XPageLoopDirection = "UP";
            XRowLoopDuration = 1.0d;

            XIsAllRowLoop = true;
            XIsShowWhenNull = false;
            XIsPageLoop = true;
            XPageRowCount = 3;

            XHeaderBorderBrush = new BrushEx(new SolidColorBrush(Colors.White));
            XHeaderBorderThickness = new Thickness(1);
            XHeaderForeground = new BrushEx(new SolidColorBrush(Colors.White));
            XHeaderBackground = new BrushEx(new SolidColorBrush(Color.FromRgb(0x00, 0x99, 0x33)));
            XRowBackground = new BrushEx(new SolidColorBrush(Colors.White));
            XOddRowBackground = new BrushEx(new SolidColorBrush(Color.FromRgb(0xc6, 0xe0, 0xb3)));
            XIsShowHeaderBorder = true;
            XIsShowRowBorder = false;
            XHeaderHeight = 80;
            XRowFont = new FontFamily("微软雅黑");
            XOddRowFont = new FontFamily("微软雅黑");
            XRowHeight = 40;
            XRowFontSize = 24;
            XHeaderFontSize = 30;
            XOddRowFontSize = 24;

            SetDefaultDataResult();
            InitializeComponent();
        }
        private void SetDefaultDataResult()
        {
            Columns = new List<GridColumn>();
            for (int i = 1; i <= 3; i++)
            {
                GridColumn column = new GridColumn();
                column.Name = "模拟数据" + i;
                column.Caption = "模拟数据" + i;
                column.DataItemId = "data" + i;
                Columns.Add(column);
            }
            Random random = new Random();
            ServiceProxy.DataServiceRef.DataSeries[] series = new ServiceProxy.DataServiceRef.DataSeries[5];
            for (int j = 1; j <= 5; j++)
            {
                ServiceProxy.DataServiceRef.DataItem[] tmpItems = new ServiceProxy.DataServiceRef.DataItem[3];
                for (int i = 1; i <= 3; i++)
                {
                    tmpItems[i - 1] = new ServiceProxy.DataServiceRef.DataItem();
                    tmpItems[i - 1].Id = "data" + i;
                    tmpItems[i - 1].Name = "data" + i;
                    tmpItems[i - 1].Value = random.NextDouble().ToString("F2");
                }
                series[j - 1] = new ServiceProxy.DataServiceRef.DataSeries();
                series[j - 1].Id = "series" + j;
                series[j - 1].Name = "series" + j;
                series[j - 1].DataItems = tmpItems;
            }
            DataResult = new ServiceProxy.DataServiceRef.DataResult();
            DataResult.DataSeries = series;
        }
        /// <summary>
        /// 从非激活状态到激活状态
        /// </summary>
        protected override void OnActive(PartContext context)
        {
            gd.Children.Clear();
            gd.RowDefinitions.Clear();
            gd.ColumnDefinitions.Clear();
            _leafColumns = BuildHeader(gd, Columns);
            _headerGridRowCount = gd.RowDefinitions.Count;
            if (XIsShowWhenNull)
            {
                _dataSpliter = new DataResultLoopSpliter2();
            }
            else
            {
                _dataSpliter = new DataResultLoopSpliter();
            }

            base.OnActive(context);
        }
        protected override void OnApplyXProperty()
        {
            if (gd == null || Columns == null || XWidth == 0 || double.IsNaN(XWidth))
            {
                return;
            }
            base.OnApplyXProperty();
            gd.Children.Clear();
            gd.RowDefinitions.Clear();
            gd.ColumnDefinitions.Clear();
            _leafColumns = BuildHeader(gd, Columns);
            _headerGridRowCount = gd.RowDefinitions.Count;
            if (XIsShowWhenNull)
            {
                _dataSpliter = new DataResultLoopSpliter2();
            }
            else
            {
                _dataSpliter = new DataResultLoopSpliter();
            }
        }
        /// <summary>
        /// 从激活状态到非激活状态
        /// </summary>
        protected override void OnDeactive(PartContext context)
        {
            //gd.Children.Clear();
            //gd.ColumnDefinitions.Clear();

            if (_loopTimer != null)
            {
                _loopTimer.Tick -= _loopTimer_Tick;
                _loopTimer.Stop();
                _loopTimer = null;
                Logger.DebugToTag(Library.LogDispatcherTimer, string.Format("组件：{0}的滚动定时器停止", this.Name));
            }

            // 清除数据行
            if (Rows.Count > 0)
            {
                gd.RowDefinitions.RemoveRange(_headerGridRowCount, gd.RowDefinitions.Count - _headerGridRowCount);
                for (int index = 0; index < Rows.Count; index++)
                {
                    Rows[index].Remove(gd);
                }
                Rows.Clear();
            }

            base.OnDeactive(context);
        }

        protected override void OnDestory()
        {
            if (_loopTimer != null)
            {
                _loopTimer.Tick -= _loopTimer_Tick;
                _loopTimer.Stop();
                _loopTimer = null;
                Logger.DebugToTag(Library.LogDispatcherTimer, string.Format("组件：{0}的滚动定时器停止", this.Name));
            }

            // 清除数据行
            if (Rows.Count > 0)
            {
                gd.RowDefinitions.RemoveRange(_headerGridRowCount, gd.RowDefinitions.Count - _headerGridRowCount);
                for (int index = 0; index < Rows.Count; index++)
                {
                    Rows[index].Remove(gd);
                }
                Rows.Clear();
            }

            base.OnDestory();
        }

        #region override

        protected override void OnDataBinding(ServiceProxy.DataServiceRef.DataResult dataResult)
        {
            if (Columns == null || _dataSpliter == null)
            {
                return;
            }

            if (dataResult != null
                && dataResult.DataSeries != null
                && dataResult.DataSeries.Count() > 0)
            {
                _HeaderCount = gd.RowDefinitions.Count;

                BindGrid(dataResult);
            }
            else if (XIsShowWhenNull)
            {
                SetDataRowWhenNull();
            }

            // 如果第一次加载数据，启动滚动事件
            if (XIsPageLoop != null && XIsPageLoop.Value && (XPageRowCount == null || dataResult.DataSeries.Length >= XPageRowCount))
            {
                if (XPageLoopInterval == null)
                {
                    XPageLoopInterval = 5;
                }

                if (_loopTimer == null)
                {
                    _loopTimer = new System.Windows.Threading.DispatcherTimer();
                    _loopTimer.Tick += _loopTimer_Tick;
                    if (XIsAllRowLoop)
                    {
                        // 所有行一起滚动
                        _loopTimer.Interval = TimeSpan.FromSeconds(XPageLoopInterval.Value + XRowLoopDuration);
                    }
                    else
                    {
                        _loopTimer.Interval = TimeSpan.FromSeconds(XPageLoopInterval.Value + _displayRowCount * XRowLoopDuration);
                    }
                    _loopTimer.Start();
                    Logger.DebugToTag(Library.LogDispatcherTimer, string.Format("组件：{0}的滚动定时器构造并启动", this.Name));
                }
                else
                {
                    _loopTimer.Start();
                    Logger.DebugToTag(Library.LogDispatcherTimer, string.Format("组件：{0}的滚动定时器已经构造，直接启动", this.Name));
                }
            }
            else
            {
                if (_loopTimer != null)
                {
                    _loopTimer.Stop();
                    _loopTimer.Tick -= _loopTimer_Tick;
                    _loopTimer = null;
                }
                Logger.DebugToTag(Library.LogDispatcherTimer, string.Format("组件：{0}的滚动定时器停止", this.Name));
            }
        }

        void _loopTimer_Tick(object sender, EventArgs e)
        {
            if (IsActived && DataResult != null)
            {
                // 数据行显示的动画持续时间
                double rowAnimationDuration = 0;
                if (_displayRowCount > 0)
                {
                    rowAnimationDuration = this.XDataAnimationDuration / _displayRowCount;
                }

                if (XPageLoopRowCount != null)
                {
                    _pageIndex += XPageLoopRowCount.Value;
                }
                else
                {
                    _pageIndex++;
                }
                if (_pageIndex >= DataResult.DataSeries.Length)
                {
                    _pageIndex = _pageIndex - DataResult.DataSeries.Length;
                }
                // 取下一次的数据
                List<DataSeries> dataSeriesList = null;
                if (XIsPageLoop != null && XIsPageLoop.Value)
                {
                    dataSeriesList = _dataSpliter.Split(DataResult, _displayRowCount, _pageIndex, ConvertToEnum(this.XPageLoopDirection));
                }
                else
                {
                    dataSeriesList = _dataSpliter.Split(DataResult, _displayRowCount, _pageIndex, DataGridRowUpdateDirection.Up);
                }

                // 获取数据行片段
                if (!string.IsNullOrEmpty(XAsNullValues))
                {
                    _asNullValueSegments = XAsNullValues.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                }

                for (int index = 0; index < Rows.Count; index++)
                {
                    DataSeries dataSeries = dataSeriesList[index];
                    Script.DataSeriesScriptObject dataSeriesScriptObj = new Script.DataSeriesScriptObject(dataSeries);

                    DataGridRow dataGridRow = Rows[index];

                    for (int columnIndex = 0; columnIndex < _leafColumns.Count; columnIndex++)
                    {
                        GridColumn column = _leafColumns[columnIndex];

                        DataItem dataItem = null;
                        for (int y = 0; y < dataSeries.DataItems.Length; y++)
                        {
                            if (dataSeries.DataItems[y].Id == column.DataItemId)
                            {
                                dataItem = dataSeries.DataItems[y];
                                break;
                            }
                        }

                        DataGridCell border = new DataGridCell();
                        Grid cellContainer = new Grid();
                        cellContainer.HorizontalAlignment = HorizontalAlignment.Center;

                        ColumnDefinition prefixCol = new ColumnDefinition();
                        prefixCol.Width = new GridLength(0, GridUnitType.Auto);
                        cellContainer.ColumnDefinitions.Add(prefixCol);

                        ColumnDefinition textCol = new ColumnDefinition();
                        textCol.Width = new GridLength(1, GridUnitType.Star);
                        cellContainer.ColumnDefinitions.Add(textCol);

                        ColumnDefinition suffixCol = new ColumnDefinition();
                        suffixCol.Width = new GridLength(0, GridUnitType.Auto);
                        cellContainer.ColumnDefinitions.Add(suffixCol);

                        List<ConditionControl> prefixs = new List<ConditionControl>();
                        List<ConditionControl> suffixs = new List<ConditionControl>();
                        SetColumnImage(column, prefixs, suffixs, dataSeries, dataSeriesScriptObj, dataItem);

                        StackPanel prefixContainer = new StackPanel();
                        prefixContainer.Orientation = Orientation.Horizontal;
                        cellContainer.Children.Add(prefixContainer);
                        Grid.SetColumn(prefixContainer, 0);
                        foreach (ConditionControl prefix in prefixs)
                        {
                            prefixContainer.Children.Add(prefix);
                            border.AddConditionControl(prefix);
                        }

                        TextBlock tb = new TextBlock();
                        tb.Text = ResolveItemText(dataItem, column);
                        // 设置文本格式
                        SetTextFormat(tb, dataGridRow.RowIndex, column);

                        cellContainer.Children.Add(tb);
                        Grid.SetColumn(tb, 1);

                        StackPanel suffixContainer = new StackPanel();
                        suffixContainer.Orientation = Orientation.Horizontal;
                        cellContainer.Children.Add(suffixContainer);
                        Grid.SetColumn(suffixContainer, 2);
                        foreach (ConditionControl suffix in suffixs)
                        {
                            suffixContainer.Children.Add(suffix);
                            border.AddConditionControl(suffix);
                        }
                        //if (suffixContainer.Children.Count > 0)
                        //{
                        //    suffixContainer.Margin = new Thickness(0, 0, 5, 0);
                        //}

                        //添加边框
                        SetRowStyle(border, dataGridRow.RowIndex, columnIndex);
                        border.Child = cellContainer;

                        #region 设置单元格的对其模式
                        if (!string.IsNullOrWhiteSpace(column.HAlignment))
                        {
                            if (column.HAlignment.ToUpper() == "RIGHT")
                            {
                                cellContainer.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                            }
                            else if (column.HAlignment.ToUpper() == "LEFT")
                            {
                                cellContainer.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                            }
                            else
                            {
                                cellContainer.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                            }
                        }
                        cellContainer.Margin = column.Padding;
                        #endregion

                        border.Height = dataGridRow.Height;
                        border.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                        border.VerticalAlignment = System.Windows.VerticalAlignment.Center;

                        dataGridRow.ReplaceCell(border, columnIndex);
                    }
                    if (XIsAllRowLoop)
                    {
                        dataGridRow.AttackToGrid(gd, _headerGridRowCount, 0, rowAnimationDuration, XRowLoopDuration);
                    }
                    else
                    {
                        dataGridRow.AttackToGrid(gd, _headerGridRowCount, dataGridRow.RowIndex * XRowLoopDuration, rowAnimationDuration, XRowLoopDuration);
                    }
                }
            }
        }

        #endregion

        private void BindGrid(ServiceProxy.DataServiceRef.DataResult dataResult)
        {
            this._dataResult = dataResult;
            //SetDataPage(dataResult);
            SetDataRow();
        }

        private void ClearPage()
        {
            if (gd.RowDefinitions.Count > 1)
            {
                List<UIElement> elements = new List<UIElement>();
                for (int i = 0; i < gd.Children.Count; i++)
                {
                    UIElement element = gd.Children[i];
                    int elementIndex = Grid.GetRow(element);
                    if (elementIndex >= _HeaderCount)
                    {
                        elements.Add(element);
                    }
                }
                foreach (UIElement element in elements)
                {
                    gd.Children.Remove(element);
                }
                gd.RowDefinitions.RemoveRange(_HeaderCount, gd.RowDefinitions.Count - _HeaderCount);
            }
        }

        /// <summary>
        /// 设置数据页
        /// </summary>
        /// <param name="dataResult"></param>
        private void SetDataPage(ServiceProxy.DataServiceRef.DataResult dataResult)
        {
            if (XPageRowCount.HasValue)
            {
                _PageCount = Convert.ToInt32(Math.Ceiling((double)dataResult.DataSeries.Length / XPageRowCount.Value));
            }
            if (_PageCount == 0)
            {
                if (!_dataPage.ContainsKey(0))
                {
                    _dataPage.Add(0, dataResult.DataSeries.ToList());
                }
            }
            else
            {
                for (int pageIndex = 0; pageIndex < _PageCount; pageIndex++)
                {
                    var vDataSeries = dataResult.DataSeries.ToList().Skip(pageIndex * XPageRowCount.Value).Take(XPageRowCount.Value);
                    if (vDataSeries != null && vDataSeries.Any())
                    {
                        if (!_dataPage.ContainsKey(pageIndex))
                        {
                            _dataPage.Add(pageIndex, vDataSeries.ToList());
                        }
                    }
                }
            }

        }
        /// <summary>
        /// 设置数据行
        /// </summary>
        private void SetDataRow()
        {
            // 获取需要显示的行数
            if (XPageRowCount == null)
            {
                _displayRowCount = DataResult.DataSeries.Length;
            }
            else if (XPageRowCount.Value > DataResult.DataSeries.Length && !XIsShowWhenNull)
            {
                _displayRowCount = DataResult.DataSeries.Length;
            }
            else
            {
                _displayRowCount = XPageRowCount.Value;
            }

            // 数据行显示的动画持续时间
            double rowAnimationDuration = 0;
            if (_displayRowCount > 0)
            {
                rowAnimationDuration = this.XDataAnimationDuration / _displayRowCount;
            }

            List<DataSeries> dataSeriesList = null;

            if (XIsPageLoop != null && XIsPageLoop.Value)
            {
                dataSeriesList = _dataSpliter.Split(DataResult, _displayRowCount, _pageIndex, ConvertToEnum(this.XPageLoopDirection));
            }
            else
            {
                dataSeriesList = _dataSpliter.Split(DataResult, _displayRowCount, _pageIndex, DataGridRowUpdateDirection.Up);
            }

            // 获取数据行片段
            if (!string.IsNullOrEmpty(XAsNullValues))
            {
                _asNullValueSegments = XAsNullValues.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            }
            if (Rows != null && Rows.Count > 0)
            {
                Rows.Clear();
            }
            for (int seriesIndex = 0; seriesIndex < dataSeriesList.Count; seriesIndex++)
            {
                DataSeries dataSeries = dataSeriesList[seriesIndex];
                Script.DataSeriesScriptObject dataSeriesScriptObj = new Script.DataSeriesScriptObject(dataSeries);

                RowDefinition row = new RowDefinition();
                row.Height = new GridLength(Math.Floor(XRowHeight.HasValue ?
                    XRowHeight.Value : (XHeight - XHeaderHeight) / dataSeriesList.Count));

                gd.RowDefinitions.Add(row);
                int rowIndex = seriesIndex;

                DataGridRow dataGridRow = new DataGridRow(rowIndex, ConvertToEnum(this.XPageLoopDirection));
                dataGridRow.Height = row.Height.Value;

                for (int columnIndex = 0; columnIndex < _leafColumns.Count; columnIndex++)
                {
                    GridColumn column = _leafColumns[columnIndex];

                    DataGridCell border = new DataGridCell();

                    Grid cellContainer = new Grid();

                    DataItem dataItem = null;
                    if (dataSeries.DataItems != null)
                    {
                        for (int y = 0; y < dataSeries.DataItems.Length; y++)
                        {
                            if (dataSeries.DataItems[y].Id == column.DataItemId)
                            {
                                dataItem = dataSeries.DataItems[y];
                                break;
                            }
                        }
                        ColumnDefinition prefixCol = new ColumnDefinition();
                        prefixCol.Width = new GridLength(0, GridUnitType.Auto);
                        cellContainer.ColumnDefinitions.Add(prefixCol);

                        ColumnDefinition textCol = new ColumnDefinition();
                        textCol.Width = new GridLength(1, GridUnitType.Star);
                        cellContainer.ColumnDefinitions.Add(textCol);

                        ColumnDefinition suffixCol = new ColumnDefinition();
                        suffixCol.Width = new GridLength(0, GridUnitType.Auto);
                        cellContainer.ColumnDefinitions.Add(suffixCol);

                        List<ConditionControl> prefixs = new List<ConditionControl>();
                        List<ConditionControl> suffixs = new List<ConditionControl>();
                        SetColumnImage(column, prefixs, suffixs, dataSeries, dataSeriesScriptObj, dataItem);

                        StackPanel prefixContainer = new StackPanel();
                        prefixContainer.Orientation = Orientation.Horizontal;
                        cellContainer.Children.Add(prefixContainer);
                        Grid.SetColumn(prefixContainer, 0);
                        foreach (ConditionControl prefix in prefixs)
                        {
                            prefixContainer.Children.Add(prefix);
                            border.AddConditionControl(prefix);
                        }

                        TextBlock tb = new TextBlock();
                        tb.Text = ResolveItemText(dataItem, column);
                        // 设置文本格式
                        SetTextFormat(tb, rowIndex, column);

                        cellContainer.Children.Add(tb);
                        Grid.SetColumn(tb, 1);

                        StackPanel suffixContainer = new StackPanel();
                        suffixContainer.Orientation = Orientation.Horizontal;
                        cellContainer.Children.Add(suffixContainer);
                        Grid.SetColumn(suffixContainer, 2);
                        foreach (ConditionControl suffix in suffixs)
                        {
                            suffixContainer.Children.Add(suffix);
                            border.AddConditionControl(suffix);
                        }
                        //if (suffixContainer.Children.Count > 0)
                        //{
                        //    suffixContainer.Margin = new Thickness(0, 0, 5, 0);
                        //}
                    }
                    //添加边框
                    SetRowStyle(border, rowIndex, columnIndex);
                    border.Child = cellContainer;

                    #region 设置单元格的对其模式
                    if (!string.IsNullOrWhiteSpace(column.HAlignment))
                    {
                        if (column.HAlignment.ToUpper() == "RIGHT")
                        {
                            cellContainer.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                        }
                        else if (column.HAlignment.ToUpper() == "LEFT")
                        {
                            cellContainer.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                        }
                        else
                        {
                            cellContainer.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                        }
                    }
                    cellContainer.Margin = column.Padding;
                    #endregion

                    border.Height = dataGridRow.Height;
                    border.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                    border.VerticalAlignment = System.Windows.VerticalAlignment.Center;

                    dataGridRow.AddCell(border);
                }

                if (XIsAllRowLoop)
                {
                    dataGridRow.AttackToGrid(gd, _headerGridRowCount, 0, rowAnimationDuration, XRowLoopDuration);
                }
                else
                {
                    dataGridRow.AttackToGrid(gd, _headerGridRowCount, dataGridRow.RowIndex * XRowLoopDuration, rowAnimationDuration, XRowLoopDuration);
                }

                Rows.Add(dataGridRow);
            }
        }
        private void SetDataRowWhenNull()
        {
            Rows.Clear();
            // 数据行显示的动画持续时间
            double rowAnimationDuration = 0;
            rowAnimationDuration = this.XDataAnimationDuration / XPageRowCount.Value;

            for (int seriesIndex = 0; seriesIndex < XPageRowCount.Value; seriesIndex++)
            {
                RowDefinition row = new RowDefinition();
                row.Height = new GridLength(Math.Floor(XRowHeight.HasValue ?
                    XRowHeight.Value : (XHeight - XHeaderHeight) / XPageRowCount.Value));

                gd.RowDefinitions.Add(row);
                int rowIndex = seriesIndex;

                DataGridRow dataGridRow = new DataGridRow(rowIndex, ConvertToEnum(this.XPageLoopDirection));
                dataGridRow.Height = row.Height.Value;

                for (int columnIndex = 0; columnIndex < _leafColumns.Count; columnIndex++)
                {
                    GridColumn column = _leafColumns[columnIndex];

                    DataGridCell border = new DataGridCell();

                    Grid cellContainer = new Grid();

                    //添加边框
                    SetRowStyle(border, rowIndex, columnIndex);
                    border.Child = cellContainer;

                    border.Height = dataGridRow.Height;
                    border.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                    border.VerticalAlignment = System.Windows.VerticalAlignment.Center;

                    dataGridRow.AddCell(border);
                }
                if (XIsAllRowLoop)
                {
                    dataGridRow.AttackToGrid(gd, _headerGridRowCount, 0, rowAnimationDuration, XRowLoopDuration);
                }
                else
                {
                    dataGridRow.AttackToGrid(gd, _headerGridRowCount, dataGridRow.RowIndex * XRowLoopDuration, rowAnimationDuration, XRowLoopDuration);
                }

                Rows.Add(dataGridRow);
            }
        }

        private void SetColumnImage(GridColumn column, List<ConditionControl> prefixs, List<ConditionControl> suffixs,
            DataSeries dataSeries,
            Script.DataSeriesScriptObject dataScriptSeries,
            ServiceProxy.DataServiceRef.DataItem dataItem)
        {
            if (column.ImagePrefixs != null && column.ImagePrefixs.Any())
            {
                ConditionControl prefix = null;
                foreach (GridColumnConditionImage imagePrefix in column.ImagePrefixs)
                {
                    prefix = ConditionControlFactory.Create(this, _dataResult, dataSeries, dataItem);
                    prefix.SetProperty("Condition", imagePrefix.Condition == null ? "" : imagePrefix.Condition.Trim());
                    prefix.SetProperty("ImageSource", imagePrefix.ImageSource);
                    prefix.SetProperty("Template", CPPEI.Coolzon.Metadata.SolutionUtil.GetTemplate(PartContext.SceneMetadata, imagePrefix.TemplateName));
                    prefix.ValidateCondition();

                    prefixs.Add(prefix);
                }
            }
            if (column.ImageSuffixs != null && column.ImageSuffixs.Any())
            {
                ConditionControl suffix = null;
                foreach (GridColumnConditionImage imageSuffix in column.ImageSuffixs)
                {
                    suffix = ConditionControlFactory.Create(this, _dataResult, dataSeries, dataItem);
                    suffix.SetProperty("Condition", imageSuffix.Condition == null ? "" : imageSuffix.Condition.Trim());
                    suffix.SetProperty("ImageSource", imageSuffix.ImageSource);
                    suffix.SetProperty("Template", CPPEI.Coolzon.Metadata.SolutionUtil.GetTemplate(PartContext.SceneMetadata, imageSuffix.TemplateName));
                    suffix.ValidateCondition();

                    suffixs.Add(suffix);
                }
            }
        }

        /// <summary>
        /// 设置表格边框
        /// </summary>
        /// <param name="rowBorder"></param>
        /// <param name="rowIndex"></param>
        /// <param name="columnIndex"></param>
        private void SetRowStyle(Border rowBorder, int rowIndex, int columnIndex)
        {
            /*
             * <Trigger Property="Tag" Value="0">
                        <Setter Property="BorderBrush" Value="{Binding XHeaderBorderBrush}" />
                        <Setter Property="Background" Value="{Binding XHeaderBackground}" />
                    </Trigger>
                    <Trigger Property="Tag" Value="1">
                        <Setter Property="BorderBrush" Value="{Binding XOddRowBorderBrush}" />
                        <Setter Property="Background" Value="{Binding XOddRowBackground}" />
                    </Trigger>
                    <Trigger Property="Tag" Value="2">
                        <Setter Property="BorderBrush" Value="{Binding XRowBorderBrush}" />
                        <Setter Property="Background" Value="{Binding XRowBackground}" />
                    </Trigger>*/

            if (rowIndex == -1)
            {
                // header
                rowBorder.BorderBrush = XHeaderBorderBrush == null ? null : XHeaderBorderBrush.Brush;
                rowBorder.Background = XHeaderBackground == null ? null : XHeaderBackground.Brush;
            }
            else
            {
                if (!XIsShowRowBorder)
                {
                    rowBorder.BorderThickness = new Thickness(0, 0, 0, 0);
                }
                else
                {
                    if (columnIndex == 0)
                    {
                        rowBorder.BorderThickness = new Thickness(XRowBorderThickness.Left, 0, XRowBorderThickness.Right, XRowBorderThickness.Bottom);
                    }
                    else
                    {
                        rowBorder.BorderThickness = new Thickness(0, 0, XRowBorderThickness.Right, XRowBorderThickness.Bottom);
                    }
                }

                if (rowIndex % 2 == 0)
                {
                    // 偶数行
                    rowBorder.BorderBrush = XOddRowBorderBrush == null ? null : XOddRowBorderBrush.Brush;
                    rowBorder.Background = XOddRowBackground == null ? null : XOddRowBackground.Brush;
                }
                else
                {
                    // 奇数行
                    rowBorder.BorderBrush = XRowBorderBrush == null ? null : XRowBorderBrush.Brush;
                    rowBorder.Background = XRowBackground == null ? null : XRowBackground.Brush;
                }
            }
        }

        /// <summary>
        /// 设置文本格式
        /// </summary>
        /// <param name="textBlock"></param>
        /// <param name="rowIndex"></param>
        /// <param name="column"></param>
        private void SetTextFormat(TextBlock textBlock, int rowIndex, GridColumn column)
        {
            /*
             * 
             * 
                    <Trigger Property="Tag" Value="0">
                        <Setter Property="HorizontalAlignment" Value="Center" />
                        <Setter Property="FontSize" Value="{Binding XHeaderFontSize}" />
                        <Setter Property="FontFamily" Value="{Binding XHeaderFont}" />
                        <Setter Property="FontWeight" Value="{Binding XHeaderFontWeight}" />
                        <Setter Property="Foreground" Value="{Binding XHeaderForeground}" />
                    </Trigger>
                    <Trigger Property="Tag" Value="1">
                        <Setter Property="FontSize" Value="{Binding XOddRowFontSize}" />
                        <Setter Property="FontFamily" Value="{Binding XOddRowFont}" />
                        <Setter Property="FontWeight" Value="{Binding XOddRowFontWeight}" />
                        <Setter Property="Foreground" Value="{Binding XOddRowForeground}" />
                    </Trigger>
                    <Trigger Property="Tag" Value="2">
                        <Setter Property="FontSize" Value="{Binding XRowFontSize}" />
                        <Setter Property="FontFamily" Value="{Binding XRowFont}" />
                        <Setter Property="FontWeight" Value="{Binding XRowFontWeight}" />
                        <Setter Property="Foreground" Value="{Binding XRowForeground}" />
                    </Trigger>
             */
            if (rowIndex == -1)
            {
                //header
                textBlock.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                textBlock.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                if (XHeaderFontSize != 0)
                {
                    textBlock.FontSize = XHeaderFontSize;
                }
                if (XHeaderFont != null)
                {
                    textBlock.FontFamily = XHeaderFont;
                }
                textBlock.FontWeight = XHeaderFontWeight;
                if (XHeaderForeground != null)
                {
                    textBlock.Foreground = XHeaderForeground.Brush;
                }
            }
            else
            {
                textBlock.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                textBlock.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                textBlock.TextWrapping = TextWrapping.NoWrap;
                if (rowIndex % 2 == 0)
                {
                    // 偶数行
                    if (XOddRowFontSize != 0)
                    {
                        textBlock.FontSize = XOddRowFontSize;
                    }
                    if (XOddRowFont != null)
                    {
                        textBlock.FontFamily = XOddRowFont;
                    }
                    textBlock.FontWeight = XOddRowFontWeight;
                    if (XOddRowForeground != null)
                    {
                        textBlock.Foreground = XOddRowForeground.Brush;
                    }
                }
                else
                {
                    // 奇数行
                    if (XRowFontSize != 0)
                    {
                        textBlock.FontSize = XRowFontSize;
                    }
                    if (XRowFont != null)
                    {
                        textBlock.FontFamily = XRowFont;
                    }
                    textBlock.FontWeight = XRowFontWeight;
                    if (XRowForeground != null)
                    {
                        textBlock.Foreground = XRowForeground.Brush;
                    }
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="item"></param>
        /// <returns>-1代表未找到</returns>
        private int GetColumnIndex(DataItem item)
        {
            for (int index = 0; index < _leafColumns.Count; index++)
            {
                if (_leafColumns[index].DataItemId == item.Id)
                {
                    return index;
                }
            }
            return -1;
        }

        private string ResolveItemText(DataItem dataItem, GridColumn column)
        {
            if (dataItem != null)
            {
                if (string.IsNullOrEmpty(dataItem.Value))
                {
                    return XNullValueText;
                }
                else
                {
                    if (_asNullValueSegments != null)
                    {
                        bool isAsNull = false;
                        for (int iSegment = 0; iSegment < _asNullValueSegments.Length; iSegment++)
                        {
                            if (_asNullValueSegments[iSegment] == dataItem.Value)
                            {
                                isAsNull = true;
                                break;
                            }
                        }
                        if (isAsNull)
                        {
                            return XNullValueText;
                        }
                        else
                        {
                            string tempValue = DataFormatUtil.ToString(dataItem.Value, column.ValueType, column.TextFormat);
                            if (string.IsNullOrEmpty(tempValue))
                            {
                                return XNullValueText;
                            }
                            return tempValue;
                        }
                    }
                    else
                    {
                        string tempValue = DataFormatUtil.ToString(dataItem.Value, column.ValueType, column.TextFormat);
                        if (string.IsNullOrEmpty(tempValue))
                        {
                            return XNullValueText;
                        }
                        return tempValue;
                    }
                }
            }
            else
            {
                return XNullValueText;
            }
        }

        private DataGridRowUpdateDirection ConvertToEnum(string updateDirection)
        {
            if (updateDirection.ToUpper() == "DOWN")
            {
                return DataGridRowUpdateDirection.Down;
            }
            return DataGridRowUpdateDirection.Up;
        }
    }
}
